<template>
  <div>
    <a-card>
      <div class="table-page-search-wrapper" style="display: flex; justify-content: space-between; align-items: center">
        <div>
          <p style="font-weight: 500">请选择本次要打的标签：</p>
          <a-form layout="inline">
            <a-col>
              <a-form-item label="打标签" class="tree-row" :style="{ marginBottom: '0px', fontWeight: 500 }">
                <a-tree-select
                  v-model="treeValue"
                  style="width: 400px"
                  :tree-data="noLeafData"
                  tree-checkable
                  :show-checked-strategy="SHOW_PARENT"
                  search-placeholder="请选择要打的标签"
                  placeholder="请选择要打的标签"
                  :replaceFields="{
                    key: 'code',
                    value: 'code'
                  }"
                  :dropdownStyle="{ zIndex: '5' }"
                  @change="handleChangeTree"
                  @select="handleSelectTree"
                />
              </a-form-item>
            </a-col>
          </a-form>
        </div>
        <a-button icon="plus" @click="handleImportXls">导入标签</a-button>
      </div>
    </a-card>
    <a-card :style="{ marginTop: '24px' }" :bordered="false">
      <div class="table-page-search-wrapper">
        <FilterTree
          :treeData="paramTree"
          :searchPlaceholder="'请输入款号搜索'"
          @updateParams="updateParams"
          @updateSearchText="updateSearchText"
          :initialRootArray="initialFilterArray"
          :useActiveCodeObj="true"
        ></FilterTree>
        <a-divider></a-divider>
        <a-form layout="inline">
          <!-- <a-col :md="8" :sm="24">
            <a-form-item label="款号">
              <a-input v-model="queryParam.name" placeholder="请输入" />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="品牌">
              <a-select v-model="queryParam.brandId" placeholder="请选择" :dropdownStyle="{ zIndex: '5' }" @change="e => handleChangeSelect(e, 'brand')">
                <a-select-option value="all">全部</a-select-option>
                <a-select-option v-for="(item, index) in brandList" :key="index" :value="item.key">{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="大类">
              <a-select v-model="queryParam.bigCategoryId" placeholder="请选择" :dropdownStyle="{ zIndex: '5' }" @change="e => handleChangeSelect(e, 'big')">
                <a-select-option value="all">全部</a-select-option>
                <a-select-option v-for="(item, index) in categoryList" :key="index" :value="item.outId">{{ item.title }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="小类">
              <a-select v-model="queryParam.smallCategoryId" default-value="all" placeholder="请选择" :dropdownStyle="{ zIndex: '5' }" @change="e => handleChangeSelect(e, 'small')">
                <a-select-option value="all">全部</a-select-option>
                <a-select-option v-for="(item, index) in scategoryList" :key="index" :value="item.outId">{{ item.title }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="年份">
              <a-select v-model="queryParam.year" placeholder="请选择" default-value="all" :dropdownStyle="{ zIndex: '5' }">
                <a-select-option value="all">全部</a-select-option>
                <a-select-option v-for="(item, index) in yearsList" :key="index" :value="item.attribname">{{ item.attribname }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col> -->
          <a-col :md="8" :sm="24">
            <!-- <a-form-item label="波段">
              <a-select v-model="queryParam.bandId" placeholder="请选择" default-value="all" :dropdownStyle="{ zIndex: '5' }">
                <a-select-option value="all">全部</a-select-option>
                <a-select-option v-for="(item, index) in bandsList" :key="index" :value="item.id">{{ item.attribname }}</a-select-option>
              </a-select>
            </a-form-item> -->
            <a-form-item label="波段">
              <a-tooltip>
                <template slot="title" v-if="queryParam.bandIds && queryParam.bandIds.length > 4">
                  {{ bandsName(queryParam.bandIds, bandsList) }}
                </template>

                <a-select
                  mode="multiple"
                  :maxTagCount="4"
                  autoClearSearchValue
                  show-search
                  allowClear
                  v-model="queryParam.bandIds"
                  placeholder="请选择波段"
                  :filter-option="filterOption"
                  @change="searchList"
                >
                  <a-select-option v-for="(item, index) in bandsList" :key="index" :value="item.id">{{ item.attribname }}</a-select-option>
                </a-select>
              </a-tooltip>
            </a-form-item>
          </a-col>
          <!-- <a-col :md="24" :sm="24">
            <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden', marginBottom: 0, marginTop: '24px' }">
              <a-button icon="plus" @click="handleImportXls">导入标签</a-button>
              <a-button type="primary" style="margin-left: 8px" @click="searchList">查询</a-button>
              <a-button style="margin-left: 8px" @click="resetList">重置</a-button>
            </span>
          </a-col> -->
        </a-form>
      </div>
    </a-card>
    <a-card :style="{ marginTop: '24px' }" class="list-content">
      <div class="ant-pro-pages-list-projects-cardList" style="clear: both">
        <a-list :loading="loading" :data-source="goodsList" :grid="{ gutter: 0 }">
          <!-- <div v-if="showLoadingMore" slot="loadMore" :style="{ textAlign: 'center', marginTop: '12px', height: '32px', lineHeight: '32px' }">
              <a-spin v-if="loadingMore" />
              <a-button v-else @click="onLoadMore">
                加载更多
              </a-button>
            </div> -->
          <a-list-item slot="renderItem" slot-scope="item, index">
            <a-card class="ant-pro-pages-list-projects-card" hoverable>
              <img slot="cover" :src="item.imgurl ? item.imgurl : 'https://img.bzhz.jnbygroup.com/cloth.png'" :alt="item.value" @click="toDetail(item, index)" />
              <!-- <img slot="cover" :alt="item.value" src="https://img.bzhz.jnbygroup.com/cloth.png" v-else @click="toDetail(item)" /> -->
              <div class="cardItemContent">
                <h3>款号：{{ item.name }}</h3>
                <p class="title">{{ item.colorno }} / {{ item.color_name }}</p>
                <p class="price">{{ item.value }}</p>
                <p class="price">吊牌价：¥{{ item.price }}.00</p>
              </div>
              <div class="btn">
                <a-button type="link" icon="edit" :loading="item.iconLoading" @click="addGoodsTags(item, index)" block>打标签</a-button>
              </div>
            </a-card>
          </a-list-item>
        </a-list>
        <p class="bottom-tip" v-show="showBottom && goodsList.length > 0">
          <a-spin v-if="loadingMore" />
          <span v-else>没有更多啦</span>
        </p>
      </div>
    </a-card>
    <a-back-top />
    <GoodsDetailDrawer :goodsInfo="goodsInfo" :showDrawer="showDrawer" :permisTree="departTree" @close="close" :originTreeList="originTreeList"></GoodsDetailDrawer>
    <EditGoodsTagsModal
      ref="modalGoods"
      :treeData="selectTagsTree"
      @updateEdit="updateEdit"
      :currentTotal="currentTotal"
      :total="total"
      @loadingPage="loadingPage"
      :originTreeList="originTreeList"
    ></EditGoodsTagsModal>
    <j-import-modal ref="importModal" :url="getImportUrl()" :uploadParams="getUploadParams()" @ok="importOk" :templateUrl="templateUrl()" :serviceId="1" :fileSize="5"></j-import-modal>
  </div>
</template>
<script>
import { queryDim, queryCatePermisListByDepart, queryGoods, querySelCatePerByDepart, queryCatePermisListByIds } from '@/api/goods'
import GoodsDetailDrawer from './modules/GoodsDetailDrawer'
import Tree from './modules/Tree'
import SelectTree from './modules/SelectTree'
import EditGoodsTagsModal from './modules/EditGoodsTagsModal'
import { queryUploadSuccess } from '@/assets/js/common'
import globalData from '@/assets/js/common'
import JImportModal from '@/components/qiniuUpload/JImportModal'
import { TreeSelect } from 'ant-design-vue'
const SHOW_PARENT = TreeSelect.SHOW_PARENT
import { tagMixin } from '../mixins/tagsMixin'
import FilterTree from '@/views/box/components/FilterTree'
export default {
  mixins: [tagMixin],
  components: {
    GoodsDetailDrawer,
    Tree,
    SelectTree,
    EditGoodsTagsModal,
    JImportModal,
    FilterTree
  },
  data() {
    return {
      SHOW_PARENT,
      departTree: [],
      noLeafData: [],
      treeValue: [],
      tags: [],
      checked: [],
      updateChecked: [],
      currentChecked: [],
      selectTagsTree: [],
      queryParam: {
        brandId: 'all',
        bigCategoryId: 'all',
        smallCategoryId: 'all',
        year: 'all',
        bandId: 'all',
        mustNotLabels: []
      },
      brandList: [],
      categoryList: [],
      scategoryList: [],
      yearsList: [],
      bandsList: [],
      loading: false,
      loadingMore: false,
      showLoadingMore: false,
      goodsList: [],
      pageSize: 20,
      current: 1,
      total: 0,
      pages: 0,
      currentTotal: 0,
      goodsInfo: {},
      showDrawer: false,
      showGoodsTags: false,
      timer: null,
      originTreeList: []
    }
  },
  mounted() {
    this.getSelectList()
    this.getCate()
    this.getFilterTree()

    // const params = JSON.parse(JSON.stringify(this.queryParam))
    // this.fetchList(params)
  },
  beforeDestroy() {
    // 页面销毁后同时清除定时器，避免占用内存
    clearInterval(this.timer)
    this.timer = null
  },
  methods: {
    // 获取商品筛选条件
    getSelectList() {
      queryDim().then(res => {
        if (res.code === 0) {
          this.bandsList = res.data.bandsV2
          this.yearsList = res.data.years
          // this.categoryList = res.data.categoryTrees
          // this.scategoryList = this.categoryList[0].childCategory
          this.brandList = res.data.categoryTrees[0].brands
        } else {
          this.$message.warning(res.data.msg)
        }
      })
    },
    // 获取可选择标签
    getCate() {
      let params = {
        code: 'B05'
      }
      queryCatePermisListByDepart(params).then(res => {
        if (res.success) {
          // this.departTree = res.result
          if (res.result.length > 0) {
            this.originTreeList = JSON.parse(JSON.stringify(res.result))
            this.departTree = res.result.map(item => {
              const checked = {
                checked: [],
                checkedName: []
              }
              return { ...item, ...checked }
            })
            console.log(this.departTree)
            let arr = JSON.parse(JSON.stringify(this.departTree))
            this.noLeafData = this.handleLeaf(arr)
            console.log(this.noLeafData)
          }
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    // 处理tree的叶子
    handleLeaf(arr) {
      for (let item of arr) {
        if (!item.leaf) {
          let result = item.children.filter(value => value.leaf)
          if (result.length == item.children.length) {
            delete item.children
          } else {
            this.handleLeaf(item.children)
          }
        }
      }
      return arr
    },
    // 改变tree节点触发
    handleChangeTree(value, label, extra) {
      // console.log(value, label, extra)
      // console.log(this.treeValue)
      let data = this.getTagArr(this.treeValue)
      this.queryCatePermisList(data)
      this.searchList()
    },
    // 选择tree节点触发
    handleSelectTree(nodeValue) {
      // this.setTitle(nodeValue.value)
    },
    // 设置当前选中对象
    setTitle(title) {
      this.getSelectedItem(title, this.treeData)
      this.$nextTick(() => {
        this.treeValue = {
          label: this.defaultTitle,
          value: title
        }
      })
    },
    // 当前选中对象的title(拼接所有父级title)
    getSelectedItem(value, data, title) {
      for (let item of data) {
        //在根节点找到对应选项
        if (!title && item.value == value) {
          this.defaultTitle = item.title
        }
        //根节点未找到继续递归查找
        else if (!title && item.children) {
          this.defaultTitle = item.title
          this.getSelectedItem(value, item.children, this.defaultTitle)
        }

        //在子节点找到对应选项
        if (title && item.value == value) {
          this.defaultTitle = title + '-' + item.title
        }
        //当前子节点未找到继续递归向下查找
        else if (title && item.children) {
          this.defaultTitle = title + '-' + item.title
          this.getSelectedItem(value, item.children, this.defaultTitle)
        }
      }
    },
    // 筛选标签范围
    /* updateTags(value) {
      this.updateChecked = value
      // console.log(this.updateChecked)
    }, */
    onChange(checkedValues, item) {
      console.log('checked = ', checkedValues)
      // console.log(item)
      /* let arr = []
      let checkedName = []
      let children = item.children
      if (checkedValues.length > 0) {
        for (var i = 0; i < children.length; i++) {
          if (children[i].leaf) {
            // 叶子
            const result = checkedValues.filter(item => item == children[i].key)
            if (result.length > 0) {
              checkedName.push(children[i].title)
              arr.push(children[i])
            }
          } else {
            const nextChildren = children[i].children
            // 非叶子
            for (var j = 0; j < nextChildren.length; j++) {
              const result = checkedValues.filter(item => item == nextChildren[j].key)
              if (result.length > 0) {
                checkedName.push(nextChildren[j].title)
                arr.push(nextChildren[j])
              }
            }
          }
        }
        item.checkedName = checkedName
        // console.log(arr)
        // 有选中标签
        if (checkedName.length > 0) {
          const obj = {
            title: item.title,
            tag: checkedName,
            content: checkedName.join(','),
            arr:arr
          }
          // console.log(obj)
          if (this.tags.length == 0) {
            this.tags.push(obj)
          } else {
            let index = this.tagIndex(obj, this.tags)
            if (index != -1) {
              this.tags[index] = obj
            } else {
              this.tags.push(obj)
            }
          }
        }
        // console.log(item.checkedName)
      } else {
        const title = item.title
        const resetTags = this.tags.filter(item => item.title !== title)
        this.tags = resetTags
        item.checkedName = []
      }
      console.log(this.tags) */
    },
    /* tagIndex(obj, arr) {
      let tagIndex = -1
      for (var a = 0; a < arr.length; a++) {
        if (arr[a].title == obj.title) {
          tagIndex = a
          return tagIndex
          break
        }
      }
      return tagIndex
    }, */
    // 删除筛选条件中的标签
    /* handleClose(removedTag, index) {
      // console.log(removedTag,index)
      const tags = this.tags.filter(tag => tag.title !== removedTag.title)
      this.tags = tags
      for (var i = 0; i < this.departTree.length; i++) {
        if (removedTag.title == this.departTree[i].title) {
          this.departTree[i].checkedName = []
          this.departTree[i].checked = []
          break
        }
      }
      console.log(this.tags)
      // console.log(this.departTree)
    }, */
    // 修改筛选的tags
    /* editTags() {
      console.log(this.checked)
      if (this.checked.length > 0) {
        this.queryParam.mustNotLabels = this.checked
      } else {
        this.queryParam.mustNotLabels = []
      }
    }, */
    // 处理勾选tag
    getTagArr(tags) {
      console.log(tags)
      let allTagsPare = this.departTree.map(item => item.code)
      let arr = []

      for (var i = 0; i < allTagsPare.length; i++) {
        let item = allTagsPare[i]
        let trr = []
        trr = tags.filter(value => {
          if (value.indexOf(item) > -1) {
            return value
          }
        })
        if (trr.length > 0) {
          arr.push({
            pidCode: item,
            codes: trr
          })
        }
      }

      console.log(arr)
      return arr
    },
    // 选择要打的标签
    /* handleOkTag() {
      if (this.departTree.length > 0) {
        if (this.updateChecked.length > 0) {
          this.currentChecked = JSON.parse(JSON.stringify(this.updateChecked))
          const data = this.getTagArr(this.updateChecked)
          this.querySelectTags(data)
          this.queryCatePermisList(data)
          this.queryParam.mustNotLabels = this.currentChecked
          this.searchList()
        } else {
          this.$message.warning('请选择标签！')
        }
      } else {
        this.$router.back(-1)
      }
    }, */
    // 查询勾选的打标范围
    querySelectTags(data) {
      let params = {
        code: 'B05',
        selectedSysCateCode: data
      }
      console.log(params)
      querySelCatePerByDepart(params).then(res => {
        if (res.success) {
          this.selectTagsTree = res.result
          this.showTagModal = false
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    // 获取标签对应的商品类目
    queryCatePermisList(data) {
      let params = {
        code: 'B06',
        selectedSysCateCode: data
      }
      queryCatePermisListByIds(params).then(res => {
        if (res.code == 0) {
          this.categoryList = res.result
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    toggleTagModal() {
      this.showTagModal = true
      console.log(this.currentChecked)
    },
    // 关闭打标签范围弹窗
    handleCancelTag() {
      if (this.departTree.length > 0) {
        if (this.currentChecked.length > 0) {
          this.showTagModal = false
        } else {
          this.$router.back(-1)
          // this.$message.warning('请选择标签！')
        }
      } else {
        this.$router.back(-1)
      }
    },
    // 筛选条件
    handleChangeSelect(value, type) {
      console.log(value, type)
      switch (type) {
        case 'big':
          const option = this.categoryList.filter(item => {
            if (item.outId === value) {
              return item
            }
          })
          this.scategoryList = option[0].children
          this.queryParam.smallCategoryId = 'all'
          break
      }
    },
    // 搜索
    searchList() {
      let data = this.getTagArr(this.treeValue)
      this.queryCatePermisList(data)
      this.querySelectTags(data)
      this.queryParam.mustNotLabels = this.treeValue
      if (this.queryParam.mustNotLabels.length > 0) {
        this.loading = true
        this.showBottom = false
        this.isRefreshBool = false
        this.current = 1
        this.goodsList = []
        const param = JSON.parse(JSON.stringify(this.queryParam))
        this.fetchList(param)
      } else {
        this.$message.warning('请先选择要打的标签！')
        this.goodsList = []
        this.showLoadingMore = false
      }
    },
    // 重置
    resetList() {
      this.queryParam = {
        brandId: 'all',
        bigCategoryId: 'all',
        smallCategoryId: 'all',
        year: 'all',
        bandId: 'all',
        mustNotLabels: []
      }
      this.tags = []
      /*       for(var i=0;i<this.departTree.length;i++){
        this.departTree[i].checked=[]
        this.departTree[i].checkedName=[]
      } */
      this.searchList()
    },
    // 查询商品列表
    fetchList(param) {
      if (param.brandId === 'all') {
        delete param.brandId
      }
      if (param.bigCategoryId === 'all') {
        delete param.bigCategoryId
      }
      if (param.smallCategoryId === 'all') {
        delete param.smallCategoryId
      }
      if (param.year === 'all') {
        delete param.year
      }
      if (param.bandId === 'all') {
        delete param.bandId
      }
      if (param.name) {
        param = {
          name: param.name
        }
      }
      let data = {
        page: {
          pageNo: this.current,
          pageSize: this.pageSize
        },
        requestData: param
      }
      queryGoods(data).then(res => {
        if (res.code == 0) {
          if (res.data.length > 0) {
            this.current = res.page.pageNo
            this.total = res.page.count
            this.pages = res.page.pages
            this.currentTotal = this.current * this.pageSize
            const dataList = res.data
            this.loading = false
            this.isRefreshBool = true
            this.goodsList = this.goodsList.concat(dataList)
            if (this.current == this.pages) {
              this.loadingMore = false
              this.showBottom = true
            } else {
              this.showBottom = false
              this.loadingMore = true
            }
          } else {
            this.isRefreshBool = false
            this.loading = false
            this.showButtom = false
            this.loadingMore = false
          }
        }
      })
    },
    // 查看商品详情
    toDetail(item, index) {
      console.log(item, index)
      // this.$router.push(`/goods/detail/${item.id}`)
      this.goodsInfo = {
        productId: item.id,
        index: index
      }
      console.log(this.goodsInfo)
      this.showDrawer = true
    },
    // 关闭goodsDetail
    close(value) {
      this.showDrawer = false
    },
    // 编辑商品标签
    addGoodsTags(item, index) {
      this.$refs.modalGoods.add(item, index)
    },
    // 编辑商品标签：prev & next
    updateEdit(index) {
      this.$refs.modalGoods.add(this.goodsList[index], index)
    },
    // 导入
    handleImportXls() {
      this.$refs.importModal.show()
    },
    // 处理上传业务的后台地址
    getImportUrl() {
      return ''
    },
    getUploadParams() {
      // console.log({...globalData.uploadParams})
      return { ...globalData.uploadParams }
    },
    // 上传成功后的方法
    importOk(result) {
      let that = this
      queryUploadSuccess(this.timer, result, 60000, function (x) {
        console.log(x)
        if (x == 'done' || x == 'warning') {
          that.$refs.importModal.close()
        }
      })
    },
    templateUrl() {
      return 'https://img.bzhz.jnbygroup.com/goodsTagSample-230509.xlsx'
    }
  }
}
</script>
<style lang="less" scoped>
@import './less/index.less';
.tree-row {
  /deep/.ant-form-item-control-wrapper {
    .ant-form-item-control {
      height: initial !important;
    }
  }
}
</style>

